﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Microsoft.Exchange.WebServices.Data;
using Microsoft.Exchange.WebServices.Auth;
using System.Net;
using System.Text;
using System.Net.Mail;
using System.Net.Mime;

using System.Net.Security;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Dns;
using System.Web.Configuration;

namespace UCWebpart
{
    public class Worker  // : EmailMessage
    {

        public static List<string> getEmail()
        {
            string cString = WebConfigurationManager.ConnectionStrings["WorkFlowConnectionString"].ConnectionString;
            string strSQL = "SELECT [Mail] FROM [WorkFlow].[dbo].[RUC_Users] where IfDelete=0 and Mail like'%@kaifa%' order by Mail ";
            DataTable dt = GetDataSet(strSQL, cString).Tables[0];
            return dt.AsEnumerable().Select(p => p[0].ToString().ToLower()).ToList();
        }

        public void writeErrorMessage(string meetingroomId, Exception ex,string userName)
        {
            string errorInnerMessage;
            if (ex.InnerException != null)
            {
                errorInnerMessage = ex.InnerException.ToString().Replace("'","\"");
            }
            else
            {
                errorInnerMessage = "";
            }
            string errorMessage = ex.Message.ToString().Replace("'","\"");
            if (errorInnerMessage.Length > 1000) {
                errorInnerMessage = errorInnerMessage.Substring(0, 990);
            }
            if (errorMessage.Length > 500)
            {
                errorMessage = errorMessage.Substring(0, 490);
            }
            string conn = WebConfigurationManager.ConnectionStrings["meetingroomManagementConnectionString"].ConnectionString;
            string sql = string.Format(@"  insert into [VenueBooking].[dbo].[MTR_bas_ErrorMessage] 
                    (meetingroomId,errorInnerMessage,errorMessage,userName,errorTime)
             values ('{0}','{1}','{2}','{3}','{4}')",meetingroomId,errorInnerMessage,errorMessage,userName,DateTime.Now);
            try
            {
                doSql(sql, conn);
            }
            catch (Exception e) {
                writeErrorMessage("", e, "writeErrorMessage");
            }
        }

        public static string[] getNameAndEmail()
        {
            string cString = WebConfigurationManager.ConnectionStrings["WorkFlowConnectionString"].ConnectionString;
            string strSQL = @"SELECT [GivenName],[SN],[Description],[Title] ,[Orge2TXT],[Orge3TXT],[Mail],IfDelete FROM [WorkFlow].[dbo].[RUC_Users] 
                        where  (IfDelete is null or IfDelete=0)and Mail like '%@kaifa%' ";
            DataTable dt = GetDataSet(strSQL, cString).Tables[0];
            string[] NameAndEmail = new string[dt.Rows.Count];
            for (int i = 0; i < dt.Rows.Count; i++) {
                string item = (dt.Rows[i]["GivenName"].ToString() + dt.Rows[i]["SN"].ToString()).ToLower() + " ,"
                    + dt.Rows[i]["Description"].ToString() + " ,"
                    + dt.Rows[i]["Title"].ToString() + " ,"
                    + dt.Rows[i]["Orge2TXT"].ToString() + " ,"
                    + dt.Rows[i]["Orge3TXT"].ToString() + " ,"
                    + dt.Rows[i]["Mail"].ToString();
                item = item.Replace(", ,",",");
                NameAndEmail[i] = item;
            }
            return NameAndEmail;
        }


        public static void doSql(string strSql, string strCon) 
        {
            try
            {
                using (SqlConnection sqlConn = new SqlConnection(strCon))
                {
                    sqlConn.Open();
                    SqlCommand SCom = new SqlCommand();
                    SCom.CommandText = strSql;
                    SCom.Connection = sqlConn;
                    SCom.CommandType = CommandType.Text;
                    int num = SCom.ExecuteNonQuery();
                    sqlConn.Close();
                }
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex,"DOSQL");
            }
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="strSql">sql语句</param>
        /// <param name="strCon">连接字符串</param>
        /// <returns></returns>
        public static DataSet GetDataSet(string strSql, string strCon)
        {
            try
            {
                using (SqlConnection sqlCnn = new SqlConnection(strCon))
                {
                    sqlCnn.Open();
                    SqlDataAdapter dataAdapter = new SqlDataAdapter(strSql, sqlCnn);
                    DataSet dataSet = new DataSet();
                    dataAdapter.SelectCommand.CommandTimeout = 480;
                    dataAdapter.Fill(dataSet);
                    sqlCnn.Close();
                    return dataSet;
                }
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "GetDataSet");
                return null;
            }
        }
        /// <summary>
        /// 发送会议通知
        /// </summary>
        /// <param name="bookingID"></param>
        /// <param name="meetingStartDate"></param>
        /// <param name="startTime"></param>
        /// <param name="meetingEndDate"></param>
        /// <param name="endTime"></param>
        /// <param name="Monday"></param>
        /// <param name="Tuesday"></param>
        /// <param name="Wednesday"></param>
        /// <param name="Thursday"></param>
        /// <param name="Friday"></param>
        /// <param name="Saturday"></param>
        /// <param name="Sunday"></param>
        /// <param name="bookingType"></param>
        /// <param name="Meetingroom"></param>
        /// <param name="bookingPerson"></param>
        /// <param name="meetingTheme"></param>
        /// <param name="participants"></param>
        /// <param name="meetingAbstract"></param>
        /// <param name="specialRequestFirst"></param>
        /// <param name="specialRequestSecond"></param>
        /// <param name="bookingState"></param>
        /// <param name="isPeriodic"></param>
        /// <returns></returns>
        public string sendPeriodicMeetingMessage(string bookingID,string userName ,string participants,string cc, string meetingTheme,
            string meetingAbstract, string mtrAdd, int mtrNo, string specialRequestFirst,string specialRequestSecond, 
            DateTime st, DateTime et, string startDate, string startTime, string endDate, string endTime, string[] weeks,string passWord) 
        {
            string[] participant = participants.Split(';');
            string[] ccs = cc.Split(';');
            try
            {
                // 实例化ExchageService
                ExchangeService service1 = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                // 指定用户名，密码，和域名
                service1.Credentials = new WebCredentials(userName, passWord, "gwkf.cn");
                // 指定Exchage服务的url地址
                service1.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                // 指定邮箱账号
                service1.AutodiscoverUrl(userName + "@kaifa.cn");
               // ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
               //// service.TraceEnabled = true;
               // service.Credentials = new WebCredentials("jundu", "470061490", "kaifa.cn");
               // service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                Appointment appointment = new Appointment(service1);
                appointment.Subject =meetingTheme;
                appointment.Body = string.Format(meetingAbstract);
                appointment.Start = st;
                appointment.End = new DateTime(st.Year,st.Month,st.Day,et.Hour,et.Minute,et.Second);// appointment.Start.AddHours(1);
                appointment.Location = mtrAdd;//

                foreach (string par in participant)
                {
                    if (par.Contains("@"))
                    {
                        string str = par.Trim();
                        appointment.RequiredAttendees.Add(str);
                    }
                }
                //appointment
                Microsoft.Exchange.WebServices.Data.DayOfTheWeek[] days = new Microsoft.Exchange.WebServices.Data.DayOfTheWeek[weeks.Length];
                int s = 0;
                foreach (string weekday in weeks)
                {
                    if (weekday == "Monday") days[s] = DayOfTheWeek.Monday;
                    else if (weekday == "Tuesday") days[s] = DayOfTheWeek.Tuesday;
                    else if (weekday == "Wednesday") days[s] = DayOfTheWeek.Wednesday;
                    else if (weekday == "Thursday") days[s] = DayOfTheWeek.Thursday;
                    else if (weekday == "Friday") days[s] = DayOfTheWeek.Friday;
                    else if (weekday == "Saturday") days[s] = DayOfTheWeek.Saturday;
                    else if (weekday == "Sunday") days[s] = DayOfTheWeek.Sunday;
                    s = s + 1;
                }
               
                appointment.Recurrence = new Recurrence.WeeklyPattern(
                    appointment.Start.Date,
                    1,
                    days
                     );
                appointment.Recurrence.StartDate = appointment.Start.Date;
                appointment.Recurrence.EndDate = new DateTime(et.Year, et.Month, et.Day);
                // Save the recurring series.
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                #region
                /*
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                service.Credentials = new NetworkCredential(userName, "hsw852123", "kaifa.cn");
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;

                service.AutodiscoverUrl(userName+"@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式
                Appointment appointment = new Appointment(service);
                appointment.Subject = meetingTheme;//
                appointment.Body = meetingAbstract;
                appointment.Start = st;
                appointment.End = et;
                appointment.ICalUid = bookingID;
                appointment.Location = mtrAdd;

                foreach (string par in participant)
                {
                    if (par.Contains("@"))
                    {
                        appointment.RequiredAttendees.Add(par);
                    }
                }
                Microsoft.Exchange.WebServices.Data.DayOfTheWeek[] weekdays = new Microsoft.Exchange.WebServices.Data.DayOfTheWeek[weeks.Length];
                int s = 0;
                foreach (string weekday in weeks)
                {
                    if (weekday == "Monday") weekdays[s] =DayOfTheWeek.Monday;
                    else if (weekday == "Tuesday") weekdays[s] = DayOfTheWeek.Tuesday;
                    else if (weekday == "Wednesday") weekdays[s] = DayOfTheWeek.Wednesday;
                    else if (weekday == "Thursday") weekdays[s] = DayOfTheWeek.Thursday;
                    else if (weekday == "Friday") weekdays[s] = DayOfTheWeek.Friday;
                    else if (weekday == "Saturday") weekdays[s] = DayOfTheWeek.Saturday;
                    else if (weekday == "Sunday") weekdays[s] = DayOfTheWeek.Sunday;
                    s = s + 1;
                }
                DayOfTheWeek[] days2 = new DayOfTheWeek[] 
                { 
                    DayOfTheWeek.Monday,
                    DayOfTheWeek.Wednesday 
                };
                appointment.Recurrence = new Recurrence.WeeklyPattern(
                    appointment.Start.Date,
                    1,
                    weekdays
                    );
                appointment.Recurrence.StartDate = appointment.Start.Date;
                appointment.Recurrence.EndDate = new DateTime(et.Year, et.Month, et.Day);
               
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                string aa = appointment.Id.UniqueId;
                */
                #endregion
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return null;
        }


        private static ExchangeService getService(String userEmail, String login, String password, String hostName)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
            AutodiscoverService auservice = new AutodiscoverService(hostName);
            if (auservice.ServerInfo != null)
            {
                try
                {
                    service.AutodiscoverUrl(userEmail);
                }
                catch (AutodiscoverRemoteException ex)
                {
                    Console.WriteLine("Exception thrown: " + ex.Error.Message);
                }

            }
            else
            {
                service.Url = new Uri("https://" + hostName + "/EWS/Exchange.asmx");
            }

            service.UseDefaultCredentials = true;


            if (service.ServerInfo == null)
            {
                service.Credentials = new WebCredentials(login, password);
            }
            return service;
        }

        public void sendRecurrenceApp()
        {
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                service.Credentials = new NetworkCredential("shengweihu", "hsw852123", "kaifa.cn");
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;
                service.AutodiscoverUrl("shengweihu@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式
                //// 实例化ExchageService
                //ExchangeService service1 = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                //// 指定用户名，密码，和域名
                //service1.Credentials = new WebCredentials("shengweihu", "hsw852123", "gwkf.cn");
                //// 指定Exchage服务的url地址
                //service1.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                //// 指定邮箱账号
                //service1.AutodiscoverUrl("shengweihu@kaifa.cn");
                Appointment appointment = new Appointment(service);
                // Set properties on the appointment.
                appointment.Subject = "Bi-Weekly(Monday, Wednesday)";
                appointment.Body = "This one hour appointment will recur on Monday and Wednesday of every second week.";
                appointment.Start = new DateTime(2014, 1, 2, 10, 0, 0);
                appointment.End = appointment.Start.AddHours(1);
                appointment.Location = "莲花山公园";
                appointment.RequiredAttendees.Add("jundu@kaifa.cn");
                // Set the recurrence information on the appointment.
                // The appointment will recur on Monday and Wednesday of every second week, effective January 1, 2009, through March 31, 2009.
                DayOfTheWeek[] days2 = new DayOfTheWeek[] { DayOfTheWeek.Monday, DayOfTheWeek.Wednesday };
                appointment.Recurrence = new Recurrence.WeeklyPattern(
                    appointment.Start.Date,
                    1,
                    days2
                     );
                appointment.Recurrence.StartDate = appointment.Start.Date;
                appointment.Recurrence.EndDate = new DateTime(2014, 3, 31);
                // Save the recurring series.
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
            }
            catch (Exception e)
            {
                string s = e.Message;
            }
        }

        public string cancelMeetingMessage(string bookingID)//, DateTime meetingStartTime, DateTime meetingEndTime, bool isPeriodic,
        //           string bookingType, string mtrAdd, int mtrNo, string bookingPerson, string meetingTheme, string participants,
        //           string meetingAbstract, string specialRequestFirst, string specialRequestSecond, string bookingState
        {
           //string[] participant = participants.Split(';');
            //#region 发送会议通知代码
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                //service.Credentials = new NetworkCredential("mespublisher", "mes_2011", "gwkf.cn");
                service.Credentials = new NetworkCredential("", "", "gwkf.cn");
                //service.AutodiscoverUrl("dancao@kaifa.cn");

                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;
                //service.AutodiscoverUrl("shengweihu@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式

                Appointment appointment = Appointment.Bind(service, new ItemId("AAMkA="));

                //appointment.Delete(DeleteMode.MoveToDeletedItems,SendCancellationsMode.SendOnlyToAll);


                CancelMeetingMessage cancelMessage = appointment.CreateCancelMeetingMessage();
                cancelMessage.Body = new MessageBody("This meeting is being canceled due to poor weather.");
                cancelMessage.IsReadReceiptRequested = true;
                cancelMessage.SendAndSaveCopy();
            }
            catch (Exception e)
            {
                Console.Write(e.StackTrace);
            }
            return "会议通知发送成功";
        }


        public string sendMeetingMessage(string bookingID, DateTime meetingStartTime, DateTime meetingEndTime, bool isPeriodic,
                    string bookingType, string mtrAdd, int mtrNo, string bookingPerson, string meetingTheme, string participants,
                    string meetingAbstract, string specialRequestFirst, string specialRequestSecond, string bookingState)
        {
            string[] participant = participants.Split(';');
            //#region 发送会议通知代码
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = false;
                
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");

                service.UseDefaultCredentials = false;
                service.AutodiscoverUrl("qifanjian@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式

                //AutodiscoverService autodiscover = new AutodiscoverService("kaifa.cn");
                //autodiscover.Credentials = new NetworkCredential("name", "pwd", "domain");
                //GetUserSettingsResponse response = autodiscover.GetUserSettings(
                //"qifanjian@kaifa.cn",
                //UserSettingName.ExternalEwsUrl,
                //UserSettingName.InternalEwsUrl);

                //Appointment appointment1 = Appointment.Bind(service,new ItemId());

                Appointment appointment = new Appointment(service);
                appointment.ICalUid = bookingID;
                appointment.Subject = meetingTheme;//
                appointment.Body = meetingAbstract;
                appointment.Start = meetingStartTime;
                appointment.End = meetingEndTime;

                //appointment.Sender.Item = new EmailAddressType();
                //appointment.Sender.Item.EmailAddress = "user1@example.com";

                //appointment.Recurrence = new Recurrence.WeeklyPattern(
                //    appointment.Start,
                //    1,/*每一周一次*/
                //    DayOfWeek.Saturday
                //    );

                appointment.Location = mtrAdd;
                //appointment.delete(DeleteMode.MoveToDeletedItems,
                //        SendCancellationsMode.SendToAllAndSaveCopy);
                foreach (string par in participant)
                {
                    if (par.Contains("@"))
                    {
                        appointment.RequiredAttendees.Add(par);
                    }
                }
                //appointment.RequiredAttendees.Add("shengweihu@kaifa.cn");
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                string aas = appointment.Id.UniqueId;
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return "会议通知发送成功";
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static string sendEmailMessage(string mailTo, string mailSubject, string mailFrom, string mailBody)
        {
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                //service.Credentials = new NetworkCredential("mespublisher", "mes_2011", "kaifa.cn");
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;
                EmailMessage msg = new EmailMessage(service);
                msg.Subject = mailSubject;
                msg.From = mailFrom;
                msg.Body = mailBody;
                msg.ToRecipients.Add(mailTo);
                msg.SendAndSaveCopy();
            }
            catch (Exception ex)
            {
                Worker w = new Worker();
                w.writeErrorMessage("0", ex, "sendEmailMessage");
            }
            return null;
        }

        /// <summary>
        /// test
        /// </summary>
        public void SendMeetingRequest(DateTime startTime, DateTime endTime, string location, string subject,
            string description, string[] attendees,string[] cc, string guid,
            bool iscancel, string orgUsername, string orgEmail, bool isSelf,string passWord)
        {
            try
            {
                ContentType type;
                string host = "mail.kaifa.cn";
                string address = orgEmail;//"qifanjian@kaifa.cn"; 
                //Helper.ReadConfigValue(dt, "friendlyname").ToString();
                string s = "25";
                string content = BuildIcsFormatString(startTime, endTime, location, subject,
                    description, attendees, guid, iscancel, orgUsername, orgEmail, "sys", "sys@kaifa.cn", isSelf);
                if (iscancel)
                {
                    type = new ContentType("text/calendar; method=CANCEL");
                }
                else
                {
                    type = new ContentType("text/calendar; method=REQUEST");
                }
                AlternateView item = AlternateView.CreateAlternateViewFromString(content, type);
                MailMessage message = new MailMessage();

                if (attendees != null)
                {
                    foreach (string str9 in attendees)
                    {
                        if (str9.Contains("@"))
                        {
                            string str8 = str9.Trim();
                            message.To.Add(str8);
                        }
                    }
                    message.To.Add(orgEmail);
                }
                if (cc != null)
                {
                    foreach (string str9 in cc)
                    {
                        if (str9.Contains("@"))
                        {
                            string str8 = str9.Trim();
                            message.CC.Add(str8);
                        }
                    }
                }
                message.From = new MailAddress(address);//
                message.AlternateViews.Add(item);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;

                SmtpClient client = new SmtpClient(host, int.Parse(s));
                //NetworkCredential credential = new NetworkCredential(userName, password);
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(orgUsername, passWord, "gwkf.cn");
                client.Send(message);
            }
            catch (Exception ex) {
                writeErrorMessage("0", ex, "SendMeetingRequest");
            }
        }

        public string BuildIcsFormatString(DateTime startTime, DateTime endTime, string location, string subject,
            string description, string[] attendees, string guid, bool iscancel, string orgUsername, string orgEmail,
            string sysOrganizer, string sysEmail, bool isSelf)
        {
            //int num = 1;
            startTime = startTime.AddHours((double)-8);
            endTime = endTime.AddHours((double)-8);
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("BEGIN:VCALENDAR");
            builder.AppendLine("VERSION:2.0");
            if (iscancel)
            {
                builder.AppendLine("METHOD:CANCEL");
            }
            else
            {
                builder.AppendLine("METHOD:REQUEST");
            }
            builder.AppendLine("BEGIN:VEVENT");
            if (attendees != null)
            {
                foreach (string str in attendees)
                {
                    if (str.Contains("@"))
                    {
                        string con = str.Trim();
                        builder.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:mailto:" + con);
                    }
                }
            }

            builder.AppendLine("CLASS:PUBLIC");
            builder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            builder.AppendLine("DESCRIPTION:" + description);
            builder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime));
            builder.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            builder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime));
            if (isSelf)
            {
                builder.AppendLine("ORGANIZER;CN=\"" + sysOrganizer + "\":mailto:" + sysEmail); //发件人
            }
            else
            {
                builder.AppendLine("ORGANIZER;CN=\"" + orgUsername + "\":mailto:" + orgEmail);
            }
            builder.AppendLine("SEQUENCE:0");
            builder.AppendLine("UID:" + guid);
            builder.AppendLine("LOCATION:" + location);
            builder.AppendLine("SUMMARY;LANGUAGE=en-us:" + subject);
            builder.AppendLine("BEGIN:VALARM");
            builder.AppendLine("TRIGGER:-PT15M");
            builder.AppendLine("ACTION:DISPLAY");
            builder.AppendLine("DESCRIPTION:Reminder");
            builder.AppendLine("END:VALARM");
            builder.AppendLine("END:VEVENT");
            builder.AppendLine("END:VCALENDAR");
            return builder.ToString();
        }




        //取消会议邮件
        public string BuildCancelMeetingRequest(DateTime start, DateTime end, string attendees, string organizer, string subject, string description, string UID, string location)
        {

            System.Text.StringBuilder sw = new System.Text.StringBuilder();


            sw.AppendLine("BEGIN:VCALENDAR");
            sw.AppendLine("VERSION:2.0");
            sw.AppendLine("METHOD:CANCEL");
            sw.AppendLine("BEGIN:VEVENT");
            sw.AppendLine(attendees);
            sw.AppendLine("CLASS:PUBLIC");
            sw.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            sw.AppendLine("DESCRIPTION:" + description);
            sw.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end));
            sw.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            sw.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start));
            sw.AppendLine("ORGANIZER;CN=\"NAME\":mailto:" + organizer);
            sw.AppendLine("SEQUENCE:0");
            sw.AppendLine("UID:" + UID);
            sw.AppendLine("LOCATION:" + location);
            sw.AppendLine("SUMMARY;LANGUAGE=en-us:" + subject);
            sw.AppendLine("BEGIN:VALARM");
            sw.AppendLine("TRIGGER:-PT720M");
            sw.AppendLine("ACTION:DISPLAY");
            sw.AppendLine("DESCRIPTION:Reminder");
            sw.AppendLine("END:VALARM");
            sw.AppendLine("END:VEVENT");
            sw.AppendLine("END:VCALENDAR");
            return sw.ToString();
        }
       /* meetingInfo = BuildCancelMeetingRequest(start, end, attendees, organizer, subject, description, UID, location);           

        System.Net.Mime.ContentType mimeType = new System.Net.Mime.ContentType("text/calendar; method=REQUEST");
        AlternateView ICSview = AlternateView.CreateAlternateViewFromString(meetingInfo,mimeType);
        MailMessage message = new MailMessage();
        message.To.Add(to);
        message.From = new MailAddress(from);
        message.AlternateViews.Add(ICSview);
        SmtpClient client = new SmtpClient();
        client.Send(message);
        */






    }
}